//
//  UIView+utils.m
//  helper
//
//  Created by huangyi on 12-10-29.
//  Copyright (c) 2012年 huangyi. All rights reserved.
//

#import "UIView+utils.h"
#import <QuartzCore/QuartzCore.h>
#import <objc/runtime.h>
#import "UIColor+utils.h"
#import "UIFont+utils.h"
#import "NSArray+utils.h"
#import "NSString+path.h"

#define userInfoKey "toolboxUserInfoKey"
#define uuidKey "toolboxUuidKey"

NSArray* getStyleFromString(NSString *str){
    static NSDictionary *themeTable=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        themeTable=[NSDictionary dictionaryWithContentsOfFile:@"theme.xml".mediaPath];
    });
    NSString *styles=themeTable[str];
    NSArray *css=[styles componentsSeparatedByString:@";"];
    return css;
}

void setColorForView(UIView *view,NSString* str){
    UIColor *color=UIColorFromString(str);
    view.layer.backgroundColor=color.CGColor;
}

void setBorderForView(UIView *view,NSString* str){
    NSString *val=str;
    NSString *radius=@"0";
    NSArray *args=[str componentsSeparatedByString:@"@"];
    if (args.count==2) {
        val=[args objectAtIndex:0];
        radius=[args objectAtIndex:1];
    }
    UIColor *color=UIColorFromString(val);
    view.layer.borderColor=color.CGColor;
    view.layer.borderWidth=1.0;
    view.layer.cornerRadius=radius.intValue;
}

void setTextColorForView(UIView *view,NSString* str){
    UIColor *color=UIColorFromString(str);
    if([view isKindOfClass:[UILabel class]]) {
        UILabel *label=(id)view;
        label.textColor=color;
    }
    if([view isKindOfClass:[UIButton class]]) {
        UIButton *button=(id)view;
        [button setTitleColor:color forState:UIControlStateNormal];
    }
    if([view isKindOfClass:[UITextView class]]) {
        UITextView *textview=(id)view;
        textview.textColor=color;
    }
    if([view isKindOfClass:[UITextField class]]){
        UITextField *textfield=(id)view;
        textfield.textColor=color;
    }
}

void setTextFontForView(UIView *view,NSString* str){
    UIFont *font=UIFontFromString(str);
    if([view isKindOfClass:[UILabel class]]) {
        UILabel *label=(id)view;
        label.font=font;
    }
    if([view isKindOfClass:[UIButton class]]) {
        UIButton *button=(id)view;
        button.titleLabel.font=font;
    }
    if([view isKindOfClass:[UITextView class]]) {
        UITextView *textview=(id)view;
        textview.font=font;
    }
    if([view isKindOfClass:[UITextField class]]){
        UITextField *textfield=(id)view;
        textfield.font=font;
    }
}

@implementation UIView (utils)

-(id)userInfo{
    id info=objc_getAssociatedObject(self, userInfoKey);
    return info;
}
-(void)setUserInfo:(id)userInfo{
    objc_setAssociatedObject(self, userInfoKey, userInfo, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSString*)uuid{
    NSString *uuid=objc_getAssociatedObject(self, uuidKey);
    return uuid;
}
-(void)setUuid:(NSString *)uuid{
    objc_setAssociatedObject(self, uuidKey, uuid, OBJC_ASSOCIATION_RETAIN);
}

-(UIImage*)imageFromView{
    CGFloat scale=[UIScreen mainScreen].scale;
    CGSize size=CGSizeMake(self.bounds.size.width*scale, self.bounds.size.height*scale);
    UIGraphicsBeginImageContext(size);
    CGContextRef ctx=UIGraphicsGetCurrentContext();
    CGContextScaleCTM(ctx,1.0f,1.0f);
    [self.layer renderInContext:ctx];
    UIImage* snapshot=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshot;
}

-(void)removeAllSubviews{
	while (self.subviews.count) {
		UIView *subview=[self.subviews objectAtIndex:0];
		[subview removeFromSuperview];
	}
}

-(UIView*)subviewWithTag:(NSInteger)tag{
    UIView *view=nil;
    for (int i=0; i<self.subviews.count; i++) {
        UIView *subview=self.subviews[i];
        if (subview.tag==tag) {
            view=subview;
        }
    }
    return view;
}

-(CGPoint)cp{
    return CGPointMake(CGRectGetWidth(self.bounds)/2, CGRectGetHeight(self.bounds)/2);
}


-(void)inspector{
    self.layer.borderWidth=1.0;
	if (self.clipsToBounds) {
		self.layer.borderColor=[UIColor redColor].CGColor;
	}else {
		self.layer.borderColor=[UIColor greenColor].CGColor;
	}
	for (UIView *subview in self.subviews) {
		[subview inspector];
	}
}

-(void)sizeToAuto{
    int width=0;
    int height=0;
    for (UIView *v in self.subviews) {
        width=MAX(width, CGRectGetMaxX(v.frame));
        height=MAX(height, CGRectGetMaxY(v.frame));
    }
    self.frame=CGRectMake(self.frame.origin.x, self.frame.origin.y, width, height);
}

//style:string
//font:string
//color:string
//border:int
//background:string
-(void)setCSS:(NSString*)style, ... NS_REQUIRES_NIL_TERMINATION{
    NSMutableArray *array=[NSMutableArray array];
    va_list args;
    va_start(args, style);
    for (NSString *str = style; str != nil; str = va_arg(args,NSString*)) {
        [array addObject:str];
    }
    va_end(args);
    while(array.count){
        NSString *str=array.firstObject;
        NSArray *sep=[str componentsSeparatedByString:@":"];
        [array removeObjectAtIndex:0];
        if(sep.count==2){
            NSString *key=sep[0];
            key=key.lowercaseString;
            NSString *val=sep[1];
            val=val.lowercaseString;
            //
            if([key isEqualToString:@"background"]){
                setColorForView(self,val);
            }
            if([key isEqualToString:@"border"]){
                setBorderForView(self, val);
            }
            if([key isEqualToString:@"font"]){
                setTextFontForView(self, val);
            }
            if([key isEqualToString:@"color"]){
                setTextColorForView(self, val);
            }
            if([key isEqualToString:@"style"]){
                NSArray *css=getStyleFromString(val);
                if(css!=nil){
                    for (NSString *str in css) {
                        [array insertObject:str atIndex:0];
                    }
                }
            }            
        }
    }
}

@end

